/*
 * Created on Jul 14, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.inspectortime.common;

/**
 *
 */
public abstract class PersistentObjectBase implements Identifiable, Comparable {

   public int hashCode() { 
      return null != getId() ? getId().toString().hashCode() : "NULL".hashCode();
   }
   
   public boolean equals( Object obj ) {
      
      if( null == obj )
         return false;
         
      // TODO: Removed this because it fails to identify two identical objects if one of them is enhanced by cglib
      /*
      if( !obj.getClass().getName().equals( getClass().getName()))
         return false;
      */  
         
      return null != getId() ? 
         getId().equals( ((PersistentObjectBase)obj).getId()) : 
         null == ((PersistentObjectBase)obj).getId();
   }

   public int compareTo( Object obj ) {
      
      if( null == obj )
         return 1;
         
      if( obj.getClass().getName().equals( getClass().getName())) {
    	  if (getId() instanceof Long) {
    		  if (null != getId()) {
    			  Long myId = (Long) getId();
    			  Long otherId = (Long) ((PersistentObjectBase)obj).getId();
    			  return myId.compareTo(otherId);
    		  } else {
    			  return -1;
    		  }  
    	  }
    	  
    	  if (getId() instanceof String) {
    		  if (null != getId()) {
    			  String myId = (String) getId();
    			  String otherId = (String) ((PersistentObjectBase)obj).getId();
    			  return myId.compareTo(otherId);
    		  } else {
    			  return -1;
    		  }  
    	  }  
    	  
    	  throw new RuntimeException("Unknown id type: " + getId().getClass().getName());
    	       
      }
         
      return getClass().getName().compareTo( obj.getClass().getName()); 
   }
   
   public String toString() {
      // TODO: Some kind of implementation based on Commons needs to be added
      // however care needs to be taken of recursive relations
      return super.toString();
   }
}